package com.gitee.tanmingjian.httptunnel.core.util;

import com.gitee.tanmingjian.httptunnel.core.bean.ConnectionInfo;

import java.io.*;
import java.net.Socket;
import java.nio.ByteBuffer;
import java.nio.charset.StandardCharsets;

public class MySQLUtils {

    /**
     * 通过MySQL的握手协议获取协议版本号和数据库版本号
     */
    public static ConnectionInfo getConnectionInfo(String host, String port) {
        //1.创建一个客户端的套换字（尝试连接）
        try(Socket socket = new Socket(host, Integer.parseInt(port))) {
            //2.获取socket通道 的输入流
            InputStream inputStream = socket.getInputStream();
            byte[] payloadLengthBuf = new byte[3];
            inputStream.read(payloadLengthBuf);
            int payloadLength = payloadLengthBuf[0];
            int sequenceId = inputStream.read();
            byte[] payloadBuf = new byte[payloadLength];
            inputStream.read(payloadBuf);
            ByteBuffer byteBuffer = ByteBuffer.wrap(payloadBuf);
            int protocolVersion = byteBuffer.get();
            ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
            while (byteBuffer.hasRemaining()) {
                byte temp = byteBuffer.get();
                if (temp == 0x00) {
                    break;
                }
                byteArrayOutputStream.write(temp);
            }
            String version = byteArrayOutputStream.toString(StandardCharsets.UTF_8.name());
            return new ConnectionInfo(host, String.valueOf(protocolVersion), version);
        } catch (IOException e) {
            throw new RuntimeException(String.format("%s:%s连接失败", host, port));
        }
    }

}
